import { login, /*logout,*/ getInfo } from '@/api/login'
import { getToken, setToken, removeToken, getName, setName, removeName } from '@/utils/auth'
import { DonMessage } from '@/utils/DonMessage'

const user = {
  state: {
    token: getToken(),
    name: getName(),
    avatar: '',
    roles: [],
    menus: [],
    menusLoad: false,
    zzjjlbdm: '' //组织机构类别代码
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
      state.menusLoad = true
    },
    // 组织机构类别代码
    SET_ZZJJLBDM: (state, zzjjlbdm) => {
      state.zzjjlbdm = zzjjlbdm
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password.trim()
      return new Promise((resolve, reject) => {
        login({ username, password }).then(response => {
          const data = response.data
          if (data === 0) {
            new DonMessage().error({
              message: '用户名或密码错误',
              type: 'error',
              duration: 5 * 1000
            })
            reject()
          } else {
            setToken(data)
            commit('SET_TOKEN', data)
            setName(username)
            commit('SET_NAME', username)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          // data.menus = []
          commit('SET_ZZJJLBDM', data.zzjgLbDm)// 组织机构类别代码
          // commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_MENUS', data.menus)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeName()
        resolve()
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 登录
    SetToken({ commit }, data) {
      return new Promise((resolve, reject) => {
        setToken(data.token)
        commit('SET_TOKEN', data.token)
        resolve()
      })
    }
  }
}

export default user
